package com.ruoyi.mentor.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.ruoyi.common.constant.OssConstants;
import com.ruoyi.mentor.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * @Author LH
 * @Description
 * @Date Create in 19:32 2021/5/23
 */
@Service
public class UploadServiceImpl implements UploadService {



    @Autowired
    OssConstants ossConstants;

    @Value("${aliyun.oss.bucket}")
    private String bucket;

    @Value("${aliyun.oss.end-point}")
    private String endPoint;

    @Value("${aliyun.oss.access-key}")
    private String accessKey;

    @Value("${aliyun.oss.access-secret}")
    private String accessSecret;


    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    public String upload(MultipartFile file) {
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKey, accessSecret);
        // 创建PutObjectRequest对象。
        // 填写Bucket名称、Object完整路径和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        String fileType = file.getOriginalFilename().split("\\.")[1];
        String fileName = new Date().getTime()+file.getOriginalFilename();
        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        String finalFileName = fileType+datePath+fileName;
        PutObjectRequest putObjectRequest = null;
        try {
            putObjectRequest = new PutObjectRequest(bucket, finalFileName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);

        // 上传文件。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();


        String url = null;
        try {
            url = "https://"+bucket+"."+endPoint+"/"+ URLEncoder.encode(finalFileName,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }
}
